package com.ruoyi.system.controller;

import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.system.domain.SysTempMenu;
import com.ruoyi.system.service.ISysTempMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.PreAuthorize;
import com.ruoyi.system.domain.SysTemplate;
import com.ruoyi.system.service.ISysTemplateService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 权限模板Controller
 * 
 * @author Ele
 * @date 2021-02-01
 */
@RestController
@RequestMapping("/template")
public class SysTemplateController extends BaseController {
    @Autowired
    private ISysTemplateService sysTemplateService;
    @Autowired
    private ISysTempMenuService tempMenuService;

    /**
     * 查询权限模板列表
     */
    @PreAuthorize(hasPermi = "system:template:list")
    @GetMapping("/list")
    public TableDataInfo list(SysTemplate sysTemplate) {
        startPage();
        List<SysTemplate> list = sysTemplateService.queryList(sysTemplate);

        return getDataTable(list);
    }

    /**
     * 导出权限模板列表
     */
    @PreAuthorize(hasPermi = "system:template:export")
    @Log(title = "权限模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysTemplate sysTemplate) throws IOException
    {
        List<SysTemplate> list = sysTemplateService.queryList(sysTemplate);
        ExcelUtil<SysTemplate> util = new ExcelUtil<SysTemplate>(SysTemplate.class);
        util.exportExcel(response, list, "template");
    }

    /**
     * 获取权限模板详细信息
     */
    @PreAuthorize(hasPermi = "system:template:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(sysTemplateService.getById(id));
    }

    /**
     * 新增权限模板
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize(hasPermi = "system:template:add")
    @Log(title = "权限模板", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysTemplate sysTemplate)
    {
        extracted(sysTemplate);
        int i = sysTemplateService.save(sysTemplate) ? 1 : 0;
        //重置菜单权限
        resetSysTempMenus(sysTemplate,sysTemplate.getMenuIds());
        return toAjax(i);
    }

    private void extracted(SysTemplate sysTemplate) {
        if(CollectionUtils.isEmpty(sysTemplate.getMenuIds())){
            throw new CustomException("权限不能为空");
        }
    }

    /**
     * 重置模板对应的菜单
     */
    private void resetSysTempMenus(SysTemplate sysTemplate, List<Integer> menuIds) {
        tempMenuService.remove(new QueryWrapper<SysTempMenu>().lambda().eq(SysTempMenu::getTempId,sysTemplate.getId()));
        SysTempMenu sysTempMenu = null;
        for (Integer menuId : menuIds) {
            sysTempMenu = new SysTempMenu();
            sysTempMenu.setTempId(sysTemplate.getId());
            sysTempMenu.setMenuId(menuId);
            tempMenuService.save(sysTempMenu);
        }
    }
    /**
     * 修改权限模板
     */
    @PreAuthorize(hasPermi = "system:template:edit")
    @Log(title = "权限模板", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysTemplate sysTemplate)
    {
        extracted(sysTemplate);
        //重置菜单权限
        resetSysTempMenus(sysTemplate,sysTemplate.getMenuIds());
        return toAjax(sysTemplateService.updateById(sysTemplate) ? 1 : 0);
    }

    /**
     * 删除权限模板
     */
    @PreAuthorize(hasPermi = "system:template:remove")
    @Log(title = "权限模板", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(sysTemplateService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
